package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.util.UploadUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@RestController
@RequestMapping("/images")
public class ImageController {
    @PostMapping
    public Object headImgUpload(MultipartFile file, HttpServletRequest request){
        /*//生成随机数
        String uuid = UUID.randomUUID().toString();
        //获取原文件名
        String originalFilename = file.getOriginalFilename();
        //获取源文件的后缀
        String ext = "." + FilenameUtils.getExtension(originalFilename);
        //新的文件名称
        String targetFileName = "/upload/" + uuid + ext;
        String contexPath= request.getSession().getServletContext().getRealPath("/");
        File targetFile = new File(contexPath,targetFileName);
        try {
            //将传入的文件写到新文件中
            FileUtils.writeByteArrayToFile(targetFile,file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("headUrl",targetFileName);
        map.put("status",true);
        return map;*/
        HashMap<String, Object> map = new HashMap<>();
        try {
            String url = UploadUtil.uploadQiniu(file);
            map.put("url",url);
            map.put("status",1);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status",0);
            map.put("msg","上传失败");
        }
        return map;
    }
}
